#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Datetime: 2022/9/27 13:51
# @Author  : CHENWang
# @Site    : 
# @File    : currency_price.py
# @Software: PyCharm

"""
脚本说明: 外汇价格相关
"""

import time
import json
import datetime as dt
import requests
import pandas as pd
from quant_researcher.quant.project_tool.wrapper_tools.common_wrappers import deco_retry
from quant_researcher.quant.project_tool.time_tool import get_today, datetime_to_timestamp, timestamp_to_str, str_to_timestamp


@deco_retry(retry=50, retry_sleep=15)
def get_currency_historical_price(symbol='USDCNH', start_date='2010-01-01', end_date=None, frequency='1d'):
    """
    从https://cn.investing.com/currencies/ 获取各外汇报价数据

    :param symbol:
    :param start_date:
    :param end_date:
    :param frequency: 支持 ['1m', '5m', '15m', '30m', '1h', '5h', '1d', '1w', '1m']
    :return:
    """

    # header = {'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/105.0.0.0 Safari/537.36',
    #           'referer': 'https://cn.investing.com/',
    #           'origin': 'https://cn.investing.com',
    #           'accept': 'application/json, text/plain, */*',
    #           'accept-encoding': 'gzip, deflate, br',
    #           'accept-language': 'en-US,en;q=0.9,zh-CN;q=0.8,zh-TW;q=0.7,zh;q=0.6'
    #           }
    # timestamp_ = int(time.time() * 1000)
    # datetime_ = timestamp_to_str(timestamp_ / 1000, fmt='%Y-%m-%d %H:%M:%S', tz_str='+0000')
    # date_ = timestamp_to_str(timestamp_ / 1000, fmt='%Y-%m-%d', tz_str='+0000')
    #
    # symbol_dict = {'USDCNH': '961728'}
    #
    # if frequency in ['1d', '1w', '1m']:
    #     frequency_dict = {'1d': 'Daily', '1w': 'Weekly', '1m': 'Monthly'}
    #     # URL地址1：https://cn.investing.com/currencies/usd-cnh-historical-data  # 可以获取足够长的历史数据，频率支持日频，周频，月频
    #     url = f'https://api.investing.com/api/financialdata/historical/' \
    #           f'{symbol_dict[symbol]}?start-date={start_date}&end-date={end_date}&time-frame={frequency_dict[frequency]}&add-missing-rows=false'
    #
    #     url = 'https://api.investing.com/api/financialdata/historical/961728?start-date=2022-08-29&end-date=2022-09-27&time-frame=Daily&add-missing-rows=false'
    # else:
    #     # URL地址2： https://cn.investing.com/currencies/usd-cnh-chart # 支持高频数据，但是历史数据长度有限
    #     resolution_list = ["1", "5", "15", "30", "45", "60", "120", "240", "300", "D", "W", "M"]
    #     ticker_url = f'https://tvc4.investing.com/db76ad47798b9e8a739c6a8dd385244b/1664258265/6/6/28/symbols?symbol=961728'
    #     url = f'https://tvc4.investing.com/11d533b0df4913a0d2774043cc6bf207/1664257504/6/6/28/history?' \
    #           f'symbol=961728&resolution=15&from=1662961511&to=1664257571'
    #
    #     # URL地址3：https://cn.investing.com/currencies/usd-cnh # 支持高频数据，但是历史数据长度有限
    #     interval_list = ['PT1M', 'PT5M', 'PT15M', 'PT30M', 'PT1H', 'PT5H', 'P1D', 'P1W', 'P1M']
    #     period_list = ['P1D', 'P1W', 'P1M', 'P3M', 'P6M', 'P1Y', 'P5Y', 'MAX']
    #     url = f'https://api.investing.com/api/financialdata/961728/historical/chart/?period=P1D&interval=PT15M&pointscount=120'

    today = dt.datetime.today()
    today = f'{today.year}_{today.month}_{today.day}'
    header = {'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/105.0.0.0 Safari/537.36'}
    url = f'https://vip.stock.finance.sina.com.cn/forex/api/jsonp.php/var _fx_s{symbol.lower()}{today}=/NewForexService.getDayKLine?symbol=fx_s{symbol.lower()}&_={today}'
    # 获取分钟频数据采用下面url
    # url = 'https://vip.stock.finance.sina.com.cn/forex/api/jsonp.php/var _fx_susdcnh_5_1664263682317=/NewForexService.getMinKline?symbol=fx_susdcnh&scale=5&datalen=1440'

    res = requests.get(url, headers=header, timeout=15)
    a = res.text.split('=("')
    b = a[1].split('");')
    c = b[0].split(',|')
    all_data_dict_list = []
    for each_data in c:
        each_data = each_data.split(',')
        data_dict = {}
        data_dict['date'] = each_data[0]
        data_dict['open'] = float(each_data[1])
        data_dict['low'] = float(each_data[2])
        data_dict['high'] = float(each_data[3])
        data_dict['close'] = float(each_data[4])
        all_data_dict_list.append(data_dict)
    all_data_df = pd.DataFrame(all_data_dict_list)

    return all_data_df


@deco_retry(retry=50, retry_sleep=15)
def get_currency_latest_price(symbol='USDCNH'):
    timestamp_ = int(time.time() * 1000)
    header = {'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/105.0.0.0 Safari/537.36',
              'Referer': 'https://finance.sina.com.cn/money/forex/hq/USDCNH.shtml'}
    url = f'https://hq.sinajs.cn/rn={timestamp_}list=fx_s{symbol.lower()}'
    res = requests.get(url, headers=header, timeout=15)
    a = res.text.split('="')
    b = a[1].split(',离岸人民币')
    c = b[0].split(',')

    latest_price = float(c[1])

    return latest_price


if __name__ == '__main__':
    get_currency_historical_price(symbol='USDCNH')

    # get_currency_latest_price(symbol='USDCNH')
